package gui;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

import terminal.Converter;
import terminal.Terminal;

import common.SpinBox;

@SuppressWarnings("serial")
public class TerminalGui extends JFrame {
	Terminal tml = new Terminal();

	JButton btnSwitch;
	TVScreen screen;
	JComboBox cbChannels;
	Timer timer;

	Image img = null;

	private boolean isRunning = false;

	public TerminalGui() {
		super("IPTV机顶盒");
		this.setLayout(new BorderLayout());

		btnSwitch = new JButton("开/关");
		btnSwitch.setBackground(Color.WHITE);
		btnSwitch.addActionListener(new ButtonListener());
		JPanel p1 = new JPanel();
		p1.add(btnSwitch);

		cbChannels = new JComboBox();
		cbChannels.addItem("CH1");
		cbChannels.addItem("CH2");
		cbChannels.addItem("CH3");
		p1.add(cbChannels);
		this.add(p1, BorderLayout.NORTH);

		JPanel p2 = new JPanel();
		screen = new TVScreen();
		screen.setSize(200, 200);
		p2.add(screen);
		this.add(p2, BorderLayout.CENTER);

		this.setSize(400, 300);
		this.setLocation(100, 100);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);

		// 定时刷新屏幕
		ActionListener taskPerformer = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				screen.repaint();
			}
		};
		timer = new Timer(500, taskPerformer);
		timer.start();
	}

	private void refresh(Graphics g) {
		int idx = cbChannels.getSelectedIndex();
		tml.setChannel(idx);
		byte data[] = tml.getData();
		if(data == null) return;
		
		if(idx == 0){	// image
			Image img = Converter.toImage(data);
			if(img != null) g.drawImage(img, 0, 0, 200, 200, this);
		}
		else if(idx == 1){	// time
			String time = Converter.toString(tml.getData());
			if(time != null) g.drawString(time, 20, 20);
		}
		else if(idx == 2){	// spin box
			double d = Converter.toDouble(data);
			SpinBox.paint(new SpinBox(d), g, 150);
		}
	}

	@SuppressWarnings("serial")
	private class TVScreen extends Canvas {
		@Override
		public void paint(Graphics g) {
			if (isRunning) {
				refresh(g);
				g.setColor(Color.RED);
				g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);
			} else {
				g.setColor(Color.BLACK);
				g.fillRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);
			}
		}
	}

	private class ButtonListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			if (!isRunning) {	// 执行开启
				isRunning = true;
				btnSwitch.setBackground(Color.GREEN);
				tml.start();
			} else {			// 执行关闭
				isRunning = false;
				btnSwitch.setBackground(Color.WHITE);
				tml.stop();
				
			}
		}

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new TerminalGui();
	}

}
